package com.test.fundible.fundible_04_home;

import static com.test.fundible.fundible_00_utils.FundibleConfigs.PermissionCode_Camera;
import static com.test.fundible.fundible_05_process.widget.OcrVie_fundiblewMana_fundibleger.Flag_StartCam_fundibleera;
import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.fundible.Othe_fundiblersInfo;
import com.test.fundible.R;
import com.test.fundible.fundible_00_customer_service.Feed_fundiblebackActivity;
import com.test.fundible.fundible_00_utils.FundibleConfigs;
import com.test.fundible.fundible_00_utils.FundibleUtil;
import com.test.fundible.fundible_00_utils.Photo_fundibleSelector_fundibleDialog;
import com.test.fundible.fundible_00_utils.image_fundible.Image_fundibleConvert;
import com.test.fundible.fundible_01_launcher.Base_fundibleApplication;
import com.test.fundible.fundible_05_process.widget.OcrVie_fundiblewMana_fundibleger;
import com.test.fundible.fundible_10_vip.VipInfoActivity_fundible;
import com.test.fundible.fundible_09_setting.Setti_fundiblengActivi_fundiblety;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.fundible_10_vip.Pers_fundibleonalIn_fundiblefo;
import com.test.fundible.fundible_00_http.OkHttpUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import pub.devrel.easypermissions.EasyPermissions;

public class PersonalCenterF_fundibleragment extends Fragment{

    private View vipBgView;
    private ImageView headIv;
    private TextView nameTv;
    private TextView mobileTv;
    private TextView upgradeDescTv;
    private ImageView vipIv;
    private TextView vTv;

    public static Bitmap HeadBm = null;

    private Runnable startCameraRunnable_fundible;
    public String imgPath_fundible = "";
    public Uri photoUri_fundible;
    private String imageUrl_fundible;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia_fundible;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fundible_personal_center, container, false);

        vipBgView = view.findViewById(R.id.ffpc_view_vipbg);
        headIv = view.findViewById(R.id.ffpc_iv_head);
        nameTv = view.findViewById(R.id.ffpc_tv_name);
        mobileTv = view.findViewById(R.id.ffpc_tv_mobile);
        upgradeDescTv = view.findViewById(R.id.ffpc_tv_upgrade_desc);
        vipIv = view.findViewById(R.id.ffpc_iv_vip);
        vTv = view.findViewById(R.id.ffpc_tv_v);

        ini_fundiblet(view);
        return view;
    }

    private void ini_fundiblet(View view){


        pickMedia_fundible = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                photoUri_fundible = uri;
                imgPath_fundible = Image_fundibleConvert.get_fundibleBitmap_fundibleFileP_fundibleathFromURI(requireContext(), photoUri_fundible);
                onPhotoGet_fundible();
            }
        });

        //my profile
        view.findViewById(R.id.ffpc_view_my_profile).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","MY_PROFILE_CLICK","");
            startActivity(new Intent(requireContext(), VipInfoActivity_fundible.class));
        });

        view.findViewById(R.id.ffpc_view_to_vip).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","VIP_CENTER_CLICK","");
            startActivity(new Intent(requireContext(), VipInfoActivity_fundible.class));
        });

        //头像点击（上传头像）
        headIv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","AVATAR_CLICK","");

            //相册选择
            new Photo_fundibleSelector_fundibleDialog(
                    requireContext(),
                    this::startCamera,//启动相机
                    this::openAlbum,//相册选择
                    "ME"
            ).show();
        });

        //feedback
        view.findViewById(R.id.ffpc_view_feedback).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","FEEDBACK_CLICK","");
            startActivity(new Intent(requireContext(), Feed_fundiblebackActivity.class));
        });

        //privacypolicy
        view.findViewById(R.id.ffpc_view_pp).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","PRIVACY_POLICY_CLICK","");
            String agreementUrl = App_fundibleShow_fundibleCustomize.getInstance_fundible().getAgreementUrl_fundible();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //setting
        view.findViewById(R.id.ffpc_view_setting).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","SETTING_CLICK","");
            startActivity(new Intent(requireContext(), Setti_fundiblengActivi_fundiblety.class));
        });

        //refresh
        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.ffpc_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            //请求用户数据
            startLoading(requireContext(),"");
            OkHttpUtil.getInstance_fundible().requestUserInfo(this::refre_fundibleshUserInfo);
        });

    }

    @Override
    public void onResume() {
        super.onResume();
//        startLoading(requireContext(),"");
        OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","START","");
        //mobile
        String encryptedMobile = FundibleUtil.getEncryptedMobile();
        mobileTv.setText(encryptedMobile);
        Log.w("---encry---", encryptedMobile );
        //请求用户数据
        OkHttpUtil.getInstance_fundible().requestUserInfo(this::refre_fundibleshUserInfo);
    }

    //刷新用户数据
    private void refre_fundibleshUserInfo(){

        stopLoading();

        //头像
        String userAvatarPath = Pers_fundibleonalIn_fundiblefo.getInstance().getUserAvatar();
        showUserAvatar(userAvatarPath);

        //全名
        String fullName = Pers_fundibleonalIn_fundiblefo.getInstance().getFullName();
        if (TextUtils.isEmpty(fullName)) nameTv.setText(getString(R.string.pc_noname));
        else nameTv.setText(fullName);

        //Vip
        refresh_fundibleVipGrade();

    }

    //初始化Vip等级显示
    @SuppressLint("SetTextI18n")
    private void refresh_fundibleVipGrade(){

        int grade = Pers_fundibleonalIn_fundiblefo.getInstance().getGrade();
        int toNextExp = Pers_fundibleonalIn_fundiblefo.getInstance().getNextGradeExp();

        switch (grade){
            case 3:
                upgradeDescTv.setText(getString(R.string.pc_upgrade_desc_max));
                vipBgView.setBackgroundResource(R.drawable.bg_vip_3);
                vipIv.setBackgroundResource(R.drawable.img_vip_3);
                vTv.setText("V3");
                break;
            case 2:
                upgradeDescTv.setText(getString(R.string.pc_upgrade_desc,String.valueOf(toNextExp),"3"));
                vipBgView.setBackgroundResource(R.drawable.bg_vip_2);
                vipIv.setBackgroundResource(R.drawable.img_vip_2);
                vTv.setText("V2");
                break;
            default:
                upgradeDescTv.setText(getString(R.string.pc_upgrade_desc,String.valueOf(toNextExp),"2"));
                vipBgView.setBackgroundResource(R.drawable.bg_vip_1);
                vipIv.setBackgroundResource(R.drawable.img_vip_1);
                vTv.setText("V1");
        }

    }

    //头像显示
    private void showUserAvatar(String imgPath){

        Runnable requestAvatarRunnable = () -> {
            if (TextUtils.isEmpty(imgPath) || !imgPath.startsWith("http")) return;
            try {
                URL url = new URL(imgPath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    HeadBm = FundibleUtil.getCircleBitmap(BitmapFactory.decodeStream(inputStream));
                    requireActivity().runOnUiThread(() -> headIv.setImageBitmap(HeadBm));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        //如果Bitmap不为空，先显示Bitmap，再启动线程获取图片
        if (HeadBm !=null){
            headIv.setImageBitmap(HeadBm);
            //启动线程获取图片
            new Thread(requestAvatarRunnable).start();
        }

        //如果Bitmap为空，先显示默认头像，再启动线程获取图片
        else {
            headIv.setImageResource(R.drawable.img_default_head);
            //启动线程获取图片
            new Thread(requestAvatarRunnable).start();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","END","");
    }

    private void startCamera() {

        OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","START_CAMERA_CLICK","");

        //拍照流程
        startCameraRunnable_fundible = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getImageFilePath_fundible();
            File imageFile = new File(imageFilePath);
            imgPath_fundible = imageFilePath;
            String providerAuthority = Base_fundibleApplication.getInstant().getPackageName() + ".file_provider";
            photoUri_fundible = FileProvider.getUriForFile(Base_fundibleApplication.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri_fundible);
            startActivityForResult(intent, Flag_StartCam_fundibleera);
        };
        //申请权限
        if (!FundibleUtil.checkPermissions_fundible(requireContext(), Manifest.permission.CAMERA)) {
            EasyPermissions.requestPermissions(requireActivity(),
                    getString(R.string.launch_permissions_camera_fundible),
                    PermissionCode_Camera, Manifest.permission.CAMERA);
        } else startCameraRunnable_fundible.run();
    }

    private void openAlbum() {

        OkHttpUtil.getInstance_fundible().uploadEventPoint("ME","OPEN_ALBUM_CLICK","");

        if (pickMedia_fundible !=null)
            pickMedia_fundible.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    /**
     * 获取图片路径
     */
    private String getImageFilePath_fundible() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath_fundible();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandboxFolderPath_fundible() {
        String inAppFolder = Base_fundibleApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += FundibleConfigs.fundibleProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }


    public void onPhotoGet_fundible() {
        if (photoUri_fundible == null) {
            imageUrl_fundible = null;
            Toast.makeText(requireContext(), getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPath_fundible)) {
            Image_fundibleConvert.start_fundibleConvert_fundibleImage(
                    new File(imgPath_fundible),
                    (localPath, thumpImg) -> {
                        startLoading(requireContext(),"");
                        new Thread(() -> OkHttpUtil.getInstance_fundible().uploadImage(localPath,() -> {
                            //上传完成
                            requireActivity().runOnUiThread(() -> {
                                stopLoading();
                                HeadBm = FundibleUtil.getCircleBitmap(thumpImg);
                                headIv.setImageBitmap(HeadBm);
                            });
                            //保存头像地址
                            Pers_fundibleonalIn_fundiblefo.getInstance().setUserAvatar(Othe_fundiblersInfo.getInstance_fundible().getImgPath_fundible());
                            Pers_fundibleonalIn_fundiblefo.getInstance().uploadUserInfo(null);
                        })).start();
                    }
            );
        } else {
            imageUrl_fundible = null;
            Toast.makeText(requireContext(), getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
        }
    }

    public void onCameraPermissionGranted(){
        if (startCameraRunnable_fundible !=null) startCameraRunnable_fundible.run();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== OcrVie_fundiblewMana_fundibleger.Flag_StartCam_fundibleera){
            onPhotoGet_fundible();
        }
    }

}